<?php
namespace app\api\controller;
use think\Input;
use think\Controller;
use app\common\controller\Base;
use app\admin\model\Networks;
use app\admin\model\Users;
use app\admin\model\Areas;
use \clt\Price as PriceClt;
class Netword extends Base{
	/*地区数据列表*/
	public function items($page=null,$key=null,$email=null,$pagelimit=10){

		$page = (int)$page > 0 ? $page : 1;
		$userId = Users::getUserId($email);
		if(intval($userId) <= 0){
			return ['code'=>-1,'msg'=>lang('User does not exist.')];
		}
		$pagelimit = intval($pagelimit) > 0 ? intval($pagelimit) : 10;
		$isCustomer = false;
		if(Users::isCustomer($userId)){//客户
			$map['m.user_id'] = $userId;
			$isCustomer = true;
		}else if(Users::isSalesman($userId) || Users::isChannel($userId)){  /*业务员|渠道员*/
			$userArr=[];
			Users::getCustomerSups($userId,$userArr);
			$map['m.user_id'] = array('in',$userArr);
		}
		//判断是否为客服服务
        if(!$isCustomer && !Users::isService($userId)){  
            $map['m.is_sn'] = 1;  //不是客户服务需要合同号的线路
        }
        if(!empty($key)){
            $map['m.name'] = array('like',"%".$key."%");
        }
        
        $network = new Networks;
        $items = $network->alias('m')
            ->join('users u',"u.admin_id = m.user_id")
            ->field('m.*,m.endcloudid as endclou,m.appro_time as approtime,m.local_cloud_id as locallabel,m.status as statuslabel,u.email,u.company,m.type as typelabel,u.email,u.address as company_address,u.tel')
            ->where($map)
            ->order('m.update_time desc,m.id desc')
            ->paginate(array('list_rows'=>$pagelimit,'page'=>$page))->toArray();
            //echo $network->getLastSql();exit;
        if($items['data']){
        	foreach($items['data'] as $k=>$vo){
        		$vo['is_out'] = 0;
        		$vo['country'] = Areas::getAreaName($vo['country_id']);
        		$vo['city'] = Areas::getAreaName($vo['city_id']);
                if($vo['status'] == 2 && strtotime($vo['enddate']) < strtotime(date('Y-m-d',time()))){ //过期
                    $vo['is_out'] = 1;
                    $vo['statuslabel'] = lang('OutTime');
                }
                $vo['item'] = $k+1;
                $data[] = [
                    'networkId' =>$vo['id'],
                	'name' =>$vo['name'],
                	'localLabel' => $vo['locallabel'],
                	'endcloud' =>$vo['endclou'],
                	'broadband'=> $vo['broadband']." Mbps",
                	'approtime' =>$vo['approtime'],
                	'statusLabel'=> $vo['statuslabel'],
                	'approtime' =>$vo['approtime'],
                	'enddate'=> $vo['enddate'],
                	'localNetwork'=> $vo['local_network'],
                	'endNetwork'=> $vo['end_network'],
                	'sn'=>empty($vo['sn']) ? '--' : $vo['sn'],
                	'total' =>$vo['total'],
                	'month' =>$vo['daylength'],
                ];
        	}
        }
        return $result = ['code'=>0,'msg'=>lang('success'),'data'=>$data,'count'=>$items['total'],'rel'=>1];
	}
    /*详情*/
    public function details($email=null,$networkId=0){
        header("Content-type:text/html;charset=utf-8");
        $userId = Users::getUserId($email);
        if(intval($userId) <= 0){
            return ['code'=>-1,'msg'=>lang('User does not exist.')];
        }
        $networks = new Networks;
        $network = $networks->where('id',$networkId)->field('*,local_cloud_id as locallabel,endcloudid as endclou,type as locatlabeladdress,status as statuslabel,type as typelabel,appro_time as approtime,endtype as endlabeladdress')->find();
        if(empty($network)){
            return ['code'=>-1,'msg'=>lang('Network does not exist.')];
        }
        /*基本信息*/
        $base = array(
            'name'=>$network->name,
            'sn'=>$network->sn,
            'ATypeLabel'=>$network->typelabel,
            'ZTypeLabel'=>$networks->typelabel[$network->endtype],
            'broadband' => $network->broadband,
            'trimbroadband' => $network->status == 8 ? $network->mbs : 0,
            'status' => $network->status,
            'statusLabel' => $network->statuslabel,
            'total' => $network->total,
            'currency' => $network->currency,
            'monthlength' => $network->daylength,
            'openTime' => $network->approtime,
            'planTime' => $network->plan_time,
            'expTime' => $network->enddate,
        );
        if(strtotime($network->enddate)+86399 < time() && $network->status == 2){
            $base['statuslabel'] = lang('OutTime');
        }
        /*本端连接*/
        $Adata = array(
            'label' => $network->locallabel,
            'address' => $network->locatlabeladdress,
            'network' => $network->local_network,
        );
        /*公有云*/
        if($network->type==3){
            $Adata['cloud_datacenter'] = getDataCenter($network->cloud_conter);
            $Adata['cloud_account'] = $network->local_cloud_userid;
            $Adata['cloud_orderId'] = $network->orderId1;
            $Adata['cloud_VPCID'] = $network->VPCID1;
            $Adata['cloud_VPC'] = $network->VPC1;
        }   
        /*对端链接*/
        $Zdata = array(
            'label' => $network->endclou,
            'address' => $network->endlabeladdress,
            'network' => $network->end_network,
        );
        /*公有云*/
        if($network->endtype==3){
            $Zdata['cloud_datacenter'] = getDataCenter($network->ecloud_conter);
            $Zdata['cloud_account'] = $network->end_userid;
            $Zdata['cloud_orderId'] = $network->orderId2;
            $Zdata['cloud_VPCID'] = $network->VPCID2;
            $Zdata['cloud_VPC'] = $network->VPC2;
        }
        $data = array('data'=>$base,'A'=>$Adata,'Z'=>$Zdata);
         return ['code'=>0,'msg'=>lang('success'),'data'=>$data];
    }
    /*创建线路*/
    public function create($email=null){
        $userId = Users::getUserId($email);
        if(intval($userId) <= 0){
            return ['code'=>-1,'msg'=>lang('User does not exist.')];
        }
        if($this->request->isPost()){
            $data = $this->request->post();
            if(empty($data['name'])){
                return ['code'=>-1,'msg'=>lang('Please enter the line name!')];
            }
            if((int)$data['type'] <= 0){
                return ['code'=>-1,'msg'=>lang('Please select the end access type!')];
            }
            /*本端接入类 公有云*/
            if((int)$data['type'] == 3){
                if((int)$data['local_cloud_id'] <= 0){
                    return ['code'=>-1,'msg'=>lang('Please choose the public cloud at this end!')];
                }
                if((int)$data['cloud_country'] <= 0){
                    return ['code'=>-1,'msg'=>lang('Please choose the local cloud connection area!')];
                }
                $data['country_id'] = (int)$data['cloud_country'];
                if((int)$data['cloud_city'] <= 0){
                    return ['code'=>-1,'msg'=>lang('Please select this end to access the city.')];
                }
                $data['city_id'] = (int)$data['cloud_city'];
                if(isAWS($data['local_cloud_id'])){  //对端是aws
                    $data['local_cloud_userid'] = $data['aws_local_cloud_userid'];
                    if(empty($data['local_cloud_userid'])){
                        return ['code'=>-1,'msg'=>lang('Please enter the end of the cloud account ID!')];
                    }
                }else{//对端是阿里云或其他
                    if(empty($data['local_cloud_userid'])){
                        switch ($data['local_cloud_id']) {
                            case 3739:
                               return ['code'=>-1,'msg'=>lang('Please enter the Pairing key')];
                                break;
                            case 3738:
                               return ['code'=>-1,'msg'=>lang('Please enter the service key')];
                                break;
                            case 3742:
                               return ['code'=>-1,'msg'=>lang('Please enter the name of the account')];
                                break;
                            default:
                                return ['code'=>-1,'msg'=>lang('Please enter the end of the cloud account ID!')];
                                break;
                        }
                    }
                    
                    if($data['local_cloud_id'] == 3742){ //华为云
                        if(empty($data['orderId1'])){
                            return ['code'=>-1,'msg'=>lang('Please enter the order number.')];
                        }
                        if(empty($data['VPCID1'])){
                            return ['code'=>-1,'msg'=>lang('Please enter the VPC ID.')];
                        }
                        if(empty($data['VPC1'])){
                            return ['code'=>-1,'msg'=>lang('Please enter the VPC available area.')];
                        }
                    }
                    
                }
                $data['local_network'] = $data['oth_local_network'];
                //本段是华为云，网络必填
                if($data['local_cloud_id'] == 3742){ //华为
                    if(empty($data['local_network']) || !valid_ip($data['local_network'])){
                        return ['code'=>-1,'msg'=>lang('Please enter the correct network!')];
                    }
                }else{
                    if(!empty($data['local_network']) && !valid_ip($data['local_network'])){
                        return ['code'=>-1,'msg'=>lang('Please enter the correct network!')];
                    }
                }
                

            }else{ //公司机构&数据中心（私有云）
                if(intval($data['country_id']) <= 0){
                    return ['code'=>-1,'msg'=>lang('Please select the local access area.')];
                }
                if((int)$data['city_id'] <= 0){
                    return ['code'=>-1,'msg'=>lang('Please select this end to access the city.')];
                }
                if((int)$data['pop_id'] <= 0){
                    return ['code'=>-1,'msg'=>lang('Please select this end POP.')];
                }
                if(!empty($data['local_network']) && !valid_ip($data['local_network'])){
                    return ['code'=>-1,'msg'=>lang('Please enter the correct network!')];
                }
            }
            /*对端数据*/
            if($data['endtype'] == 3){
                if(empty($data['endcloudid'])){
                    return ['code'=>-1,'msg'=>lang('Please select the end cloud connection type!')];
                }
                if((int)$data['endcloudaddrid'] <= 0){
                    return ['code'=>-1,'msg'=>lang('Please select the right end access area.')];
                }
                $data['ecountry_id'] = (int)$data['endcloudaddrid'];
                if((int)$data['ecloud_city'] <= 0){
                    return ['code'=>-1,'msg'=>lang('Please select the right end access city.')];
                }
                $data['ecity_id'] = (int)$data['ecloud_city'];
                if(isAWS($data['endcloudid'])){  //对端是aws
                    $data['end_userid'] = $data['aws_end_userid'];
                    if(empty($data['end_userid'])){
                        return ['code'=>-1,'msg'=>lang('Please enter the end cloud account ID!')];
                    }
                    // if(empty($data['end_aws_accessID'])){
                    //     return ['code'=>0,'msg'=>lang('Please enter the end cloud AccessID!')];
                    // }
                    // if(empty($data['end_aws_secrectKey'])){
                    //     return ['code'=>0,'msg'=>lang('Please enter the end cloud SecrectKey!')];
                    // }

                }else{  //对端是阿里云或其他
                    if(empty($data['end_userid'])){
                        switch ($data['endcloudid']) {
                            case 3739:
                                return ['code'=>-1,'msg'=>lang('Please enter the Pairing key')];
                                break;
                            case 3738:
                               return ['code'=>-1,'msg'=>lang('Please enter the service key')];
                                break;
                            case 3742:
                               return ['code'=>-1,'msg'=>lang('Please enter the name of the account')];
                                break;
                            default:
                                return ['code'=>-1,'msg'=>lang('Please enter the end account ID!')];
                                break;
                        }
                    }
                    
                    if($data['endcloudid'] == 3742){ //华为云
                        if(empty($data['orderId2'])){
                            return ['code'=>-1,'msg'=>lang('Please enter the order number.')];
                        }
                        if(empty($data['VPCID2'])){
                            return ['code'=>-1,'msg'=>lang('Please enter the VPC ID.')];
                        }
                        if(empty($data['VPC2'])){
                            return ['code'=>-1,'msg'=>lang('Please enter the VPC available area.')];
                        }
                    }
                    /*对端网络必填*/
                    if($data['endcloudid'] == 3742){
                        if(empty($data['end_network']) || !valid_ip($data['end_network'])){
                            return ['code'=>-1,'msg'=>lang('Please enter the correct end-to-end network!')];
                        }
                    }else{
                        if(!empty($data['end_network']) && !valid_ip($data['end_network'])){
                            return ['code'=>-1,'msg'=>lang('Please enter the correct end-to-end network!')];
                        }
                    }
                    
                }
            }else{
                if((int)$data['ecountry_id'] <= 0){
                    return ['code'=>0,'msg'=>lang('Please select the right end access area.')];
                }
                if((int)$data['ecity_id'] <= 0){
                    return ['code'=>-1,'msg'=>lang('Please select the right end access city.')];
                }
                if((int)$data['epop_id'] <= 0){
                    return ['code'=>-1,'msg'=>lang('Please select the right end to access POP.')];
                }
                if(!empty($data['elocal_network']) && !valid_ip($data['elocal_network'])){
                    return ['code'=>-1,'msg'=>lang('Please enter the correct end-to-end network!')];
                }
                $data['end_network'] = $data['elocal_network'];
                unset($data['elocal_network']);
            }
             if((int)$data['daylength'] <= 0){
                return ['code'=>-1,'msg'=>lang('Please choose the time to buy!')];
            }
            /*其他*/
            $data['broadband'] = (int)$data['broadband'];
            $data['user_id'] = $userId;
            $data['create_time'] = time();
            $data['status'] = 1; //1,是申请开通
            $base = [];
            $is_send = true;
            $price = new PriceClt($data);
            $total = $price->getNetworkTotal();
            $data['total'] = intval($total);
            $data['currency'] = $price->getCurrency();
            $Network = new Networks;
            $result = $Network->data($data)->allowField(true)->save();
            $id = $Network->id;
            if($result){
                //$this->notice($this->Network);
                db('network_logs')->insert(
                    array(
                        'user_id'=>$userId,
                        'network_id'=>$Network->id,
                        'status'=>$data['status'],
                        'content'=>lang('Apply for network lines'),
                        'create_time'=>time()
                    )
                );
                return ['code'=>0,'msg'=>lang('The data has been submitted.'),'url'=>U('index'),'data'=>$data];
            }
            return ['code'=>-1,'msg'=>lang('The data submission failed.')];
        }
        return ['code'=>-1,'msg'=>lang('error')];
    }
    /*查询价格*/
	public function Queryprice(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $price = new PriceClt($data);
            $total = $price->getNetworkTotal();
            if($total !== false && $total > 0){
                $total = _discount($total);
                return ['code'=>1,'msg'=>lang('Configuration Cost:')."<span class='price-money'>".prefix_free(intval($total))." / ".lang('Month')."</span>",'total'=>intval($total)];
            }
            return ['code'=>0,'msg'=>lang('Configuration Cost:')."<span class='price-money'>--- / ".lang('Month')."</span>",'total'=>0];
        }
        return ['code'=>-1,'msg'=>lang('error')];
    }
    /*删除线路的接口*/
    public function delete($email=null,$networkId=0){
        $userId = Users::getUserId($email);
        if(intval($userId) <= 0){
            return ['code'=>-1,'msg'=>lang('User does not exist.')];
        }
        $networks = new Networks;
        $network = $networks->where('id',$networkId)->field('*')->find();
        if(empty($network)){
            return ['code'=>-1,'msg'=>lang('Network does not exist.')];
        }
        if($network->delete()){
            return ['code'=>0,'msg'=>lang('success')];
        }
        return ['code'=>0,'msg'=>lang('fail')];
    }
}